const express = require("express");
const router = express.Router();
const { Op } = require("sequelize");
const db = require("../models");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.message.findAll().then((messages) => res.send(messages));
});

// router.get('/:id', verify,(req,res) => {
//     db.message.findAll({
//         where: {
//             id: req.params.id
//         }
//     }).then(message => {
//         res.send(message)
//     })
// })

router.get("/read", verify, async (req, res) => {
  const userId = req.query.userId;
  // console.log(req.query)
  const messages = await db.message.findAll({
    where: {
      [Op.and]: [
        {
          read: {
            [Op.substring]: `${userId},`,
          },
          [Op.not]: [
            {
              deleted: {
                [Op.substring]: `${userId},`,
              },
            },
          ],
        },
      ],
    },
  });
  res.send(messages);
});

// [Op.or]:[
//     {
//         read: {
//             [Op.substring]: `${userId},`
//         },
//         deleted:{
//             [Op.substring]:`${userId},`
//         }
//     }
// ]
router.get("/unread", verify, async (req, res) => {
  const userId = req.query.userId;
  const messages = await db.message.findAll({
    where: {
      [Op.not]: [
        {
          read: {
            [Op.substring]: `${userId},`,
          },
        },
      ],
    },
  });
  res.send(messages);
});

router.post("/add", verify, (req, res) => {
  const message = req.body;
  // console.log(message)

  db.message
    .create(message)
    .then((message) => {
      res.send(message);
    })
    .catch((err) => {
      res.status(400).send(err);
    });
});

router.post("/delete", verify, async (req, res) => {
  const msgId = req.body.messageId;
  const userId = req.body.userId;
  if (!msgId || !userId) {
    res.status(400).send({ msg: "请输入正确的用户ID和消息ID" });
    return;
  }
  const msg = await db.message.findOne({ where: { id: msgId } });
  if (!msg.read || msg.read.indexOf(`${userId},`) == -1) {
    res.status(400).send({ msg: "该消息未读不可删除" });
    return;
  }
  if (msg.deleted && msg.deleted.indexOf(`${userId},`) != -1) {
    res.status(400).send({ msg: "该消息已删除！" });
    return;
  }
  let deletedUsers = msg.deleted;
  deletedUsers += userId + ",";
  db.message
    .update({ deleted: deletedUsers }, { where: { id: msgId } })
    .then((updated) => {
      res.send({ deleted: updated });
    })
    .catch((err) => {
      res.send({ err: err });
    });
});

router.post("/edit", verify, (req, res) => {
  console.log(req.body);
  db.message
    .update(req.body, {
      where: {
        id: req.body.id,
      },
    })
    .then((message) => {
      res.send(message);
    })
    .catch((err) => {
      res.send(err);
    });
});

router.put("/read", verify, async (req, res) => {
  const msgId = req.body.messageId;
  const userId = req.body.userId;
  if (!msgId || !userId) {
    res.status(400).send({ msg: "请输入正确的用户ID和消息ID" });
    return;
  }
  const msg = await db.message.findOne({ where: { id: msgId } });
  if (msg.read && msg.read.indexOf(`${userId},`) != -1) {
    res.status(400).send({ msg: "该消息已读！" });
    return;
  }
  let readUsers = msg.read;
  readUsers += userId + ",";
  db.message
    .update({ read: readUsers }, { where: { id: msgId } })
    .then((updated) => {
      res.send({ updated: updated });
    })
    .catch((err) => {
      res.send({ err: err });
    });
});
module.exports = router;
